package com.demo.多线程;

import java.util.concurrent.*;

/**
 * @Program: java
 * @ClassName TestThread
 * @Author: liutao
 * @Description: 线程的创建、启动
 * @Create: 2023-10-26 21:16
 * @Version 1.0
 **/
public class ThreadDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 启动线程
        // Tread
        new TestThread("测试线程1").start();
        new TestThread("测试线程2").start();

        // Runnable
        new Thread(new TestRunnable()).start();
        new Thread(new TestRunnable()).start();

        // Callable
        // 第一种方法
        // 创建执行服务
        ExecutorService pool = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> ser1 = pool.submit(new TestCallable());
        Future<Boolean> ser2 = pool.submit(new TestCallable());
        // 获取结果
        Boolean r1 = ser1.get();
        System.out.println("result1: " + r1);
        Boolean r2 = ser2.get();
        System.out.println("result2: " + r2);
        // 关闭服务
        pool.shutdownNow();
        // 第二种方法
        FutureTask<Boolean> futureTask = new FutureTask<>(new TestCallable());
        new Thread(futureTask).start();
        Boolean r3 = futureTask.get();
        System.out.println("result3: " + r3);

        // Lambda
        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();

    }

    /**
     * 1,Thread方式
     **/
    static class TestThread extends Thread {
        public TestThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println("Thread: " + Thread.currentThread().getName());
        }
    }

    /**
     * 2,Runnable方式
     **/
    static class TestRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("Runnable: " + Thread.currentThread().getName());
        }
    }

    /**
     * 3,Callable方式
     **/
    static class TestCallable implements Callable<Boolean> {
        @Override
        public Boolean call() {
            System.out.println("Callable: " + Thread.currentThread().getName());
            return true;
        }
    }

}
